import type { Directive, DirectiveBinding } from "vue";

interface DirectiveValue {
    pastel: boolean;
    avoidExtreme: boolean;
    updateOnUpdate: boolean;
}

/**
 * 生成随机十六进制颜色
 * @param {boolean} pastel - 是否使用柔和色
 * @param {boolean} avoidExtreme - 是否避免纯黑/纯白等极端颜色
 * @returns {string} #xxxxxx 格式的颜色
 */
function getRandomColor({ pastel = false, avoidExtreme = true } = {}) {
    if (pastel) {
        // 柔和色：RGB 值在 128~255 之间，确保明亮且饱和度低
        const r = Math.floor(Math.random() * 128) + 128; // 128-255
        const g = Math.floor(Math.random() * 128) + 128;
        const b = Math.floor(Math.random() * 128) + 128;
        return `rgb(${r}, ${g}, ${b})`;
    }

    // 普通随机色（十六进制）
    const letters = "0123456789ABCDEF";
    let color = "#";
    for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }

    if (avoidExtreme) {
        // 避免纯黑 (#000000)、纯白 (#FFFFFF) 和接近黑白的颜色
        const hex = color.replace("#", "").toUpperCase();
        if (hex === "000000" || hex === "FFFFFF") {
            // 重新生成（递归，但概率极低）
            return getRandomColor({ pastel, avoidExtreme });
        }

        // 可选：避免太暗或太亮的颜色（通过亮度判断）
        const r = parseInt(hex.slice(0, 2), 16);
        const g = parseInt(hex.slice(2, 4), 16);
        const b = parseInt(hex.slice(4, 6), 16);
        // 计算相对亮度（ITU-R BT.709 标准）
        const brightness = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;

        // 亮度 < 0.1（太暗）或 > 0.9（太亮）则重新生成
        if (brightness < 0.1 || brightness > 0.9) {
            return getRandomColor({ pastel, avoidExtreme });
        }
    }

    return color;
}

const randomBg: Directive = {
    mounted(el: HTMLElement | any, binding: DirectiveBinding<DirectiveValue>) {
        const options = binding.value || {};
        const { pastel = true, avoidExtreme = true, updateOnUpdate = false } = options;

        el._randomBgOptions = { pastel, avoidExtreme, updateOnUpdate };
        el.style.backgroundColor = getRandomColor({ pastel, avoidExtreme });
    },

    updated(el, binding) {
        const { updateOnUpdate = false } = el._randomBgOptions || {};
        if (updateOnUpdate) {
            const options = binding.value || {};
            const { pastel = false, avoidExtreme = true } = options;
            el.style.backgroundColor = getRandomColor({ pastel, avoidExtreme });
        }
    }
};

export default randomBg;
